package com.scalar.chiptrack.adaptor.jsi;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.InventoryLot;
import com.scalar.chiptrack.adaptor.dao.ShippedLotDAO;
import com.scalar.chiptrack.adaptor.dao.InventoryLotDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.ScalarException;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.Locale;
import java.util.TimeZone;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Iterator;

import java.io.File;

import jxl.Workbook;
import jxl.Sheet;
import jxl.Cell;
import jxl.CellType;
import jxl.DateCell;

/**
 * Created by IntelliJ IDEA.
 * User: Sudhakar
 * Date: May 30, 2007
 * Time: 4:19:40 PM
 */
public class JSIDataParser extends JobHandler implements AdaptorConstants
{
    HashMap m_inventoryDataMap          = new HashMap();
    private Logger m_parserLogger       = null;
    private String m_dataOutputDir      = null;

    public JSIDataParser() throws ScalarException
    {
        try
        {
            m_dataOutputDir = AdaptorUtils.getDataOutputDir(VENDOR_NAME_JSI_LOGISTICS, INVENTORY_TYPE_CLASS_STORE);
            AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
            m_parserLogger =  AdaptorUtils.getDataParserLogger( m_dataOutputDir,VENDOR_NAME_JSI_LOGISTICS );
            // All the DAOs and Parser should be logging into same file
            ShippedLotDAO.setLogger(m_parserLogger);
            InventoryLotDAO.setLogger(m_parserLogger);
            AdaptorUtils.setLogger(m_parserLogger);
        }
        catch (ScalarException se)
        {
            log("ERROR!! ERROR!! ERROR!! Exception while loading JSI output directory details from database, Exception: " + se);
            throw se;
        }
    }

    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main(String args[]) throws Exception
    {
        new JSIDataParser().execute();
    }

    /**
     *
     * @throws Exception
     */
    public void execute() throws Exception
    {
        AdaptorUtils.printHeader(VENDOR_NAME_JSI_LOGISTICS, CONSTANT_PARSER );

        File doneDestDir = new File( m_dataOutputDir + "/done" );

        File wipDataoutDir = new File(m_dataOutputDir);
        File[] fileList = wipDataoutDir.listFiles();

        if ((fileList == null) || (fileList.length <= 3))
        {
            log("No file found in directory: " + wipDataoutDir);
            throw new ScalarException("No file found in directory: " + wipDataoutDir + "----\n\n");
        }

        ArrayList successFileList   = new ArrayList();
        ArrayList jsiWipList        = null;
        boolean success             = true;

        for (int i = 0; i < fileList.length; i++)
        {
            if (fileList[i].isDirectory() == true)
            {
                continue;
            }

            if (fileList[i].getName() != null && fileList[i].getName().trim().startsWith(JSIPOP3Adaptor.JSI_WIP_FILE ) )
            {
                jsiWipList = parseJsiWipsheet(fileList[i].getAbsolutePath());

                if (jsiWipList != null && jsiWipList.size() > 0)
                {
                    getJsiWipDetails(jsiWipList);
                }
                //Add files to success list to move to /done directory
                successFileList.add(fileList[i]);
            }
        }
        /*Updating the FG Lot Information*/
        try
        {
            // Save Finished Goods Information
            if (m_inventoryDataMap.isEmpty() == false)
            {
                log(" Updating Finished Goods Lot Information");
                InventoryLotDAO.saveInventoryLot(null, m_inventoryDataMap.values().iterator(), LOCATION_TYPE_FG, VENDOR_NAME_JSI_LOGISTICS);
            }
            else
            {
                InventoryLotDAO.closeInventoryLot(null, LOCATION_TYPE_FG, VENDOR_NAME_JSI_LOGISTICS);
            }
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log("ERROR!! ERROR!! ERROR!! Could not update Finished Goods Lot information into database: " + se);
            throw se;
        }

        // TO SEND THE NEW LOTS, NEW TRANSIT LOTS, NO PO LOTS, DISCREPANCY LOTS NOTIFICATIONS TO THE USER
        AdaptorDAO.sendAllNotifications(VENDOR_NAME_JSI_LOGISTICS, true, true, true);

        // To Close the Drop Out Lots
        AdaptorDAO.closeDropOutLots(VENDOR_NAME_JSI_LOGISTICS);

        int adaptor_id = AdaptorRunInfo.getLastRunAdaptorId( JSIPOP3Adaptor.ADAPTOR_NAME, CONSTANT_ADAPTOR);
        // Update Adaptor_Run_Info table
        try
        {
            if (success == true)
            {
                AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, JSIPOP3Adaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id );
                System.out.println("SUCCESSFULLY UPDATED IN THE DATABASE");
            }
            else
            {
                AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, JSIPOP3Adaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id );
            }

        }
        catch (Exception se)
        {
            success = false;
            log("WARNING!! WARNING!! WARNING!! Could not update Adaptor run information, Exception: " + se);
            throw se;
        }

        // Move the successful files to 'done' directory
        if (success)
        {
            AdaptorUtils.moveFilesToDone(successFileList, doneDestDir);
        }
    }
    /**
     * @param fileName
     * @return
     * @throws Exception
     */
    private ArrayList parseJsiWipsheet(String fileName) throws Exception
    {
        ArrayList jsiFgList = new ArrayList();
        JSIPOP3WipStatus jsifgStatus = null;
      
        if (fileName == null)
        {
            throw new ScalarException("Filename argument is null");
        }

        try
        {
            File wipStatusFile = new File(fileName);

            if (wipStatusFile.exists() == false)
            {
                throw new ScalarException(fileName + " doesnt exist");
            }

            log("\nFound " + fileName);
            log("Parsing the file for JSI FG Report...");
            System.out.println("\nFound " + fileName);
            System.out.println("Parsing the file for JSI FG Report...");

            Workbook workbook = Workbook.getWorkbook(wipStatusFile);
            Sheet sheet = workbook.getSheet(0);
            Cell[] row = null;

            for (int rowCount = 1; rowCount < sheet.getRows(); rowCount++)
            {
                row = sheet.getRow(rowCount);

                if ( row.length > 0 && row[1].getContents() != null && row[1].getContents().trim().length() > 0)
                {
                    jsifgStatus = new JSIPOP3WipStatus();

                    if (row.length > 0)
                    {
                        if (row[0].getType().equals(CellType.EMPTY))
                        {
                            jsifgStatus.setDateIn(null);
                        }
                        else if(row[0].getType().equals( CellType.DATE ))
                        {
                            DateCell dc = (DateCell) row[0];
                            java.util.Date dateIn = null;
                            dateIn = dc.getDate();

                            if ("America/Los_Angeles".equals(System.getProperty("user.timezone")))
                            {
                                Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.US);
                                cal.setTime(dateIn);
                                dateIn = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)).getTime();
                                jsifgStatus.setDateIn(StringUtils.formatDateToString(dateIn));
                            }
                            else
                            {
                                Calendar cal = new GregorianCalendar();
                                cal.setTime(dateIn);
                                dateIn = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)).getTime();
                                jsifgStatus.setDateIn(StringUtils.formatDateToString(dateIn));
                            }
                        }
                    }
                    if (row.length > 1)
                    {
                        if (row[1].getType().equals(CellType.EMPTY))
                        {
                            jsifgStatus.setPartNumber(null);
                        }
                        else
                        {
                            jsifgStatus.setPartNumber(row[1].getContents().trim());
                        }
                    }
                    if (row.length > 2)
                    {
                        if (row[2].getType().equals(CellType.EMPTY))
                        {
                            jsifgStatus.setLotNumber(null);
                        }
                        else
                        {
                            jsifgStatus.setLotNumber(row[2].getContents().trim());
                        }
                    }
                    if (row.length > 3)
                    {
                        if (row[3].getType().equals(CellType.EMPTY))
                        {
                            jsifgStatus.setQuantity(null);
                        }
                        else
                        {
                            jsifgStatus.setQuantity(row[3].getContents().trim());
                        }
                    }
                    if (row.length >4)
                    {
                        if (row[4].getType().equals(CellType.EMPTY))
                        {
                            jsifgStatus.setDateCode(null);
                        }
                        else
                        {

                            jsifgStatus.setDateCode(row[4].getContents().trim());
                        }
                    }
                    if (row.length > 5)
                    {
                        if (row[5].getType().equals(CellType.EMPTY))
                        {
                            jsifgStatus.setCoo(null);
                        }
                        else
                        {

                            jsifgStatus.setCoo(row[5].getContents().trim());
                        }
                    }
                    if (row.length > 6)
                    {
                        if (row[6].getType().equals(CellType.EMPTY))
                        {
                            jsifgStatus.setLoc(null);
                        }
                        else
                        {

                            jsifgStatus.setLoc(row[6].getContents().trim());
                        }
                    }
                    if (row.length > 7)
                    {
                        if (row[7].getType().equals(CellType.EMPTY))
                        {
                            jsifgStatus.setBoxNo(null);
                        }
                        else
                        {

                            jsifgStatus.setBoxNo(row[7].getContents().trim());
                        }
                    }
                    if (row.length > 8)
                    {
                        if (row[8].getType().equals(CellType.EMPTY))
                        {
                            jsifgStatus.setRemark(null);
                        }
                        else
                        {

                            jsifgStatus.setRemark(row[8].getContents().trim());
                        }
                    }

                    jsiFgList.add( jsifgStatus );
                }
            }
        }
        catch (Exception e)
        {
            throw new ScalarException("Exception " + e);
        }

        return jsiFgList;
    }

    /**
     *
     * @param jsiFgList
     */
    public void getJsiWipDetails(ArrayList jsiFgList)
    {
        String partNumber               = null;
        String lotNumber                = null;
        JSIPOP3WipStatus jsiFgStatus    = null;
        InventoryLot inventoryLot       = null;

        try
        {
            Iterator jsiFgIterator = jsiFgList.iterator();

            while (jsiFgIterator.hasNext())
            {
                jsiFgStatus = (JSIPOP3WipStatus) jsiFgIterator.next();

                partNumber = jsiFgStatus.getPartNumber();
                lotNumber = jsiFgStatus.getLotNumber();

                if (partNumber != null && lotNumber != null)
                {
                    inventoryLot = (InventoryLot) m_inventoryDataMap.get(lotNumber + partNumber);
                    if (inventoryLot == null)
                    {
                        inventoryLot = new InventoryLot(VENDOR_NAME_JSI_LOGISTICS, LOCATION_TYPE_FG);
                        m_inventoryDataMap.put(lotNumber + partNumber, inventoryLot);
                    }

                    int quantity = 0;
                    if (inventoryLot.getQtyIn() != null)
                    {
                        try
                        {
                            quantity = Integer.parseInt(inventoryLot.getQtyIn());
                        }
                        catch (NumberFormatException npe) {
                        }
                        try
                        {
                            quantity += Integer.parseInt(jsiFgStatus.getQuantity());
                        }
                        catch (NumberFormatException npe) {
                        }
                    }
                    else
                    {
                        try
                        {
                            quantity = Integer.parseInt(jsiFgStatus.getQuantity());
                        }
                        catch (NumberFormatException npe) {
                        }
                    }

                    String dateIn        = null;
                    String jsiDateIn = null;

                    if (inventoryLot.getDateIn() != null)
                    {
                        dateIn = inventoryLot.getDateIn();
                    }
                    if (jsiFgStatus.getDateIn() != null && jsiFgStatus.getDateIn().trim().length() > 0)
                    {
                        jsiDateIn = jsiFgStatus.getDateIn();
                    }
                    if ((jsiDateIn != null) && (dateIn != null))
                    {
                        java.util.Date tempDate1 = StringUtils.getSQLDate(jsiDateIn, "MM/dd/yyyy");
                        java.util.Date tempDate2 = StringUtils.getSQLDate(dateIn, "MM/dd/yyyy");
                        if (tempDate1 != null && tempDate2 != null)
                        {
                            if (tempDate1.compareTo(tempDate2) > 0)
                            {
                                jsiDateIn = dateIn;
                            }
                        }
                    }

                    if (quantity > 0)
                    {
                        inventoryLot.setLotNumber(lotNumber);
                        inventoryLot.setPartNumber(partNumber);
                        inventoryLot.setDateIn(jsiDateIn);
                        inventoryLot.setQtyIn(quantity + "");
                        inventoryLot.setStatus(LOT_STATUS_RUNNING);
                        inventoryLot.setFabLotNumber(jsiFgStatus.getLotNumber());
                        inventoryLot.setDateCode(jsiFgStatus.getDateCode());
                        inventoryLot.setLotCategory(LOT_CATEGORY_TYPE_PROD);
                    }
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            log("ERROR!ERROR! While parsing the JSI FG Details" + e);
            System.out.println("ERROR!ERROR! While parsing the JSI FG Details" + e);
        }
    }

    /**
     *
     */
    private void printVersionInfo()
    {
        String info = "\n\n+----------- Running JSI POP3 Data Parser on " + new java.util.Date(System.currentTimeMillis()) + " -------------+\n" +
                "\n+---------------------------------------------------------------+\n" +
                "+                                                                \n" +
                "+           JSI POP3 Data Interpreter - Beta          \n" +
                "+                                                                \n" +
                "+    Copy Right (C) 2007 - ScalarSoft Inc., All rights reserved.  \n" +
                "+                                                                \n" +
                "+---------------------------------------------------------------+\n";
        System.out.println(info);
        log(info);
    } //end of printVersionInfo

    /**
     *
     * @param message
     */
    private void log(String message)
    {
        if (message == null) return;

        if (m_parserLogger != null)
        {
            synchronized (m_parserLogger)
            {
                m_parserLogger.logDebug(message + LINE_SEPARATOR);
            }
        }
        else
        {
            System.out.println(message);
        }
    }
}
